﻿using EmailClient.Mail;
using EmailClient.Model;
using EmailClient.ViewModel;
using MahApps.Metro.Controls;
using MahApps.Metro.Controls.Dialogs;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace EmailClient.View
{
    /// <summary>
    /// Interaction logic for EmailAccountView.xaml
    /// </summary>
    public partial class EmailAccountView : MetroWindow
    {
        private EmailAccount eAccount = null;
        public SettingsView mainWindow = null;

        public EmailAccountView()
        {
            InitializeComponent();



            if (eAccount == null)
            {
                eAccount = new EmailAccount();
                this.Title = EmailClient.Properties.Resources.EmailAccountTitleNew;                
            }
            else
            {
                this.Title = EmailClient.Properties.Resources.EmailAccountTitle;
                FillFieldsOnForm();
            }
            base.DataContext = eAccount;
        }

        public EmailAccountView(EmailAccount item)
        {
            InitializeComponent();
            eAccount = item;
            this.Title = EmailClient.Properties.Resources.EmailAccountTitle;
            base.DataContext = eAccount;
            FillFieldsOnForm();
        }

        private void FillFieldsOnForm()
        {
            ucTypeServer.ServerType = eAccount.MailType;
            ucTypeServer.UseSSL = eAccount.UseSSL;
            ucInData.Sever = eAccount.inServer;
            ucInData.Port = eAccount.inPort;
            ucInData.LabelServer = EmailClient.Properties.Resources.EmailAccountUcInDataLabel;
            ucInData.PortTip = EmailClient.Properties.Resources.EmailAccountUcInDataPortTip;
            pbPass.Password = eAccount.Password;
            rtbSignature.Text = eAccount.Signature;

            ucOutDate.Sever = eAccount.outServer;
            ucOutDate.Port = eAccount.outPort;
            ucOutDate.LabelServer = EmailClient.Properties.Resources.EmailAccountucUcOutDateLabel;
            ucOutDate.PortTip = EmailClient.Properties.Resources.EmailAccountUcOutDataPortTip;
        }

        private void FillLetterFromForm()
        {
            eAccount.Signature = rtbSignature.Text;
            eAccount.FullName = Name + " <" + eAccount.Email.Trim() + ">";
            eAccount.MailType = ucTypeServer.ServerType;
            eAccount.UseSSL = ucTypeServer.UseSSL;
            eAccount.inServer = ucInData.Sever;
            eAccount.inPort = ucInData.Port;
            eAccount.Password = pbPass.Password;            
            eAccount.outServer = ucOutDate.Sever;
            eAccount.outPort = ucOutDate.Port;                     
        }

        private bool ValidateFields()
        {
            var result = true;
            //string pattern = @"^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})$";
            //Regex rgx = new Regex(pattern);
            //if (!rgx.IsMatch(this.ToSent)) 
            if (String.IsNullOrEmpty(eAccount.MailType)) result = false;
            if (String.IsNullOrEmpty(eAccount.inServer)) result = false;
            if (eAccount.inPort <= 0) result = false;
            if (ucTypeServer.ServerType == "POP3")
            {
                if (String.IsNullOrEmpty(eAccount.outServer)) result = false;
                if (eAccount.outPort <= 0) result = false;
            }
            return result;
        }

        private async void btSave_Click(object sender, RoutedEventArgs e)
        {
            FillLetterFromForm();
            if (ValidateFields())
            {
                if (eAccount.Id == 0) await AccountViewModel.Insert(eAccount);
                else await AccountViewModel.Update(eAccount);

                if (eAccount.MailType == "POP3") POP3.CreateUpdateFolders(eAccount);
                else IMAP.LoadFolders(eAccount);
                

                await Common.UpdateFolderTreeOnMainView();
                MessageBox.Show("Данные сохранены успешно.", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                if (mainWindow != null) mainWindow.FillList();
            }
            else
            {
                MessageBox.Show("Не верно заполнены реквизиты формы!", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private async void btClose_Click(object sender, RoutedEventArgs e)
        {
            var mw = (MainWindow)App.Current.MainWindow;
            await mw.UpdateTree();
            this.Close();
        }

        private async void btDel_Click(object sender, RoutedEventArgs e)
        {
            var result = await AccountViewModel.Delete(eAccount);
            var mw = (MainWindow)App.Current.MainWindow;
            await mw.UpdateTree();
            mainWindow.FillList();
            this.Close();
        }

        private void btCheck_Click(object sender, RoutedEventArgs e)
        {
            FillLetterFromForm();
            if (ucTypeServer.ServerType == "POP3")
            {
                var result = Mail.POP3.CheckData(eAccount);
                MessageBox.Show(result, "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }
            else
            {
                var result = Mail.IMAP.CheckData(eAccount);
                MessageBox.Show(result, "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
            }

        }

        private void ucTypeServer_cbType_Change(object sender, RoutedEventArgs e)
        {
            if (sender != null && ((System.Windows.Controls.ComboBox)(sender)).SelectedIndex == 1) ucInData.LabelServer = "IMAP сервер:";
            else
            {
                ucOutDate.Visibility = System.Windows.Visibility.Visible;
                ucInData.LabelServer = "Входящий сервер:";
            }
        }
    }

}
